package forecasting.converter.parser;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * This class will merge a dataset file and an expected prediction file together.
 */
public class FileJoiner {
	public FileJoiner() {}
	
	/**
	 * @param args
	 * @return TODO
	 */
	public static void main(String[] args) {
		// validate input parameters
		if(args.length != 3) {
			System.out.println(args.length);
			System.out.println("FileJoiner <dataset_file> <expected_prediction_file> <output_file>");
			System.exit(-1);
		}
		
		final String datasetFile = args[0];
		final String predictionFile = args[1];
		final String outputFile = args[2];
		
		final FileJoiner joiner = new FileJoiner();
		joiner.run(datasetFile, predictionFile, outputFile);
		System.out.println("Done!!!");
	}
	
	public void run(final String datasetFile, final String predictionFile, final String outputFile) {
		final Scanner datasetScanner = AbstractDatasetParserTemplate.openFileScanner(datasetFile);
		final Scanner predictionScanner = AbstractDatasetParserTemplate.openFileScanner(predictionFile);
		try {
			final PrintWriter outfile = new PrintWriter(outputFile);
			
			// append the 'target:numeric' column to the dataset header.
			if (datasetScanner.hasNext()) {
				final String datasetHeader = datasetScanner.nextLine();
				
				// Skip a line to keep the prediction file on the same row as the dataset file.
				predictionScanner.nextLine();
				
				outfile.println(datasetHeader + RandomForestDatasetParser.OUTPUT_FILE_DELIMITER + "class");
			}
			
			int sampleNum = 0;
			while (datasetScanner.hasNext()) {
				++sampleNum;
				if (sampleNum % 10000 == 0) {
					System.out.println("Creating output file: Processing sample #" + sampleNum);
				}
				final String dataSample = datasetScanner.nextLine();
				final String expected = predictionScanner.nextLine();
				
				System.out.println("dataSample has " + dataSample.split(RandomForestDatasetParser.OUTPUT_FILE_DELIMITER, -1).length 
						+ " columns. expected has " + expected.split(RandomForestDatasetParser.OUTPUT_FILE_DELIMITER, -1).length + " columns.");
				outfile.println(dataSample + RandomForestDatasetParser.OUTPUT_FILE_DELIMITER + expected);
			}
			outfile.close();
		} catch (FileNotFoundException e) {
			System.err.println("File not found: " + e);
		}
		
	}
}
